#pragma once
#include<iostream>
#include<string>
#include<fstream>
#include<unordered_map>
#include"Logger.hpp"

const std::string& sep=": ";

class Dictionary
{
private:
    void LoadConf()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(Loglevel::ERROR)<<"open file error";
            return;
        }
        std::string line;
        while(std::getline(in,line))
        {
            LOG(Loglevel::DEBUG) << "load dict message: " << line;
            auto pos=line.find(sep);
            if(pos==line.npos)
            {
                LOG(Loglevel::WARNING) << "format error: " << line;
                continue;
            }
            std::string key=line.substr(0,pos);
            std::string value=line.substr(pos+sep.size());
            if(key.empty()||value.empty())
            {
                LOG(Loglevel::WARNING) << "format error, word or value is empty: " << line;
                continue;
            }
            _map.insert({key,value});
        }
        in.close();
    }
public:
    Dictionary(const std::string& path)
        :_path(path)
    {
        LOG(Loglevel::INFO) << "construct Dictionary obj";
        LoadConf();
    }

    std::string Translate(const std::string &word,
         const std::string &whoip, uint16_t whoport)
    {
        (void)whoip;
        (void)whoport;
        auto iter=_map.find(word);
        if(iter==_map.end())
        {
            return "unknow";
        }
        return iter->first+" -> "+iter->second;
        
    }

    ~Dictionary()
    {}
private:
    std::string _path;
    std::unordered_map<std::string,std::string> _map;
};